package com.colin.util.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhaolz
 * @date 2022/10/27 9:45
 */
public class Unicode2JavaUtil {

    private static final Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");

    public static String word2Unicode(String str){
        char[] utfBytes = str.toCharArray();
        String result = "";
        for(int i=0;i<utfBytes.length;i++){
            String hexB = Integer.toHexString(utfBytes[i]);
            if(hexB.length()<=2){
                hexB = "00" + hexB;
            }
            result = result + "\\u" + hexB;
        }
        return result;
    }

    public static String unicode2Word(String str){
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()){
            ch = (char)Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch+"");
        }
        return str;
    }

    public static void main(String[] args) {
        System.out.println(word2Unicode("拌合"));
        System.out.println(unicode2Word("\\u62cc\\u5408"));
    }

}
